import 'dart:io';

import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:image_picker/image_picker.dart';
import 'package:provider/provider.dart';

import '../provider/post_list_provider.dart';
import '../utils/api.dart';
import '../widgets/publish_success_ani.dart';

class RentPublishPage extends StatefulWidget {
  const RentPublishPage({super.key});

  @override
  State<RentPublishPage> createState() => _RentPublishPageState();

  static Future<bool> publishPost({
    required String type,
    required String title,
    required String content,
    required List<File> images,
    String location = '',
    double? latitude,
    double? longitude,
  }) async {
    try {
      // 假设Api.uploadImage(file)会返回上传后图片的url字符串
      List<String> uploadedUrls = [];
      for (var file in images) {
        final url = await Api.uploadImage(file);
        if (url != null) uploadedUrls.add(url);
      }

      final postData = {
        'userId': 123456, // TODO: 替换成真实用户ID
        'type': type, // 传入参数 type，比如 'rent' 或 'rant'
        'title': title,
        'content': content,
        'images': uploadedUrls,
        'location': location,
        'tags': '',
        'latitude': latitude,
        'longitude': longitude,
      };

      final response = await Api.post('/cms/post/publish', body: postData);
      return true;
    } catch (e) {
      debugPrint('发布失败: $e');
      return false;
    }
  }
}

class _RentPublishPageState extends State<RentPublishPage> {
  final _formKey = GlobalKey<FormState>();
  final ImagePicker _picker = ImagePicker();
  List<File> _images = [];

  String _title = '';
  String _price = '';
  String _location = '';
  String _description = '';

  // 选择图片（支持多选）
  Future<void> _pickImages() async {
    final pickedFiles = await _picker.pickMultiImage(imageQuality: 75);
    if (pickedFiles.isNotEmpty) {
      setState(() {
        _images.addAll(pickedFiles.map((x) => File(x.path)));
        if (_images.length > 9) _images = _images.sublist(0, 9);
      });
    }
  }

  // 上传所有图片并返回URL列表
  Future<List<String>> _uploadImages() async {
    List<String> urls = [];
    for (var file in _images) {
      final url = await Api.uploadImage(file); // 你自己写的上传方法
      if (url != null) urls.add(url);
    }
    return urls;
  }

  // 提交发布
  Future<void> _submit() async {
    if (!_formKey.currentState!.validate()) return;
    _formKey.currentState!.save();

    try {
      final uploadedUrls = await _uploadImages();

      final postData = {
        'userId': 123456, // TODO 动态替换用户ID
        'type': 'rent',
        'title': _title,
        'content': _description,
        'images': uploadedUrls,
        'location': _location,
        'tags': '',
        'latitude': null,
        'longitude': null,
      };

      final response = await Api.post('/cms/post/publish', body: postData);
      final provider = Provider.of<PostListProvider>(context, listen: false);
      provider.fetchPosts(reset: true);
      if (mounted) {
        // 显示发布成功动画弹窗
        PublishSuccessOverlay.show(
          context,
          onComplete: () {
            GoRouter.of(context).go('/?tab=home');
          },
        );
      }
    } catch (e) {
      debugPrint('发布失败: $e');
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('发布失败，请重试')));
      }
    }
  }

  // 单个输入卡片封装
  Widget _buildInputCard({required Widget child}) => Container(
    padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
    margin: const EdgeInsets.symmetric(vertical: 8),
    decoration: BoxDecoration(
      color: Colors.white,
      borderRadius: BorderRadius.circular(16),
      boxShadow: [BoxShadow(color: Colors.grey.shade100, blurRadius: 10)],
    ),
    child: child,
  );

  // 图片选择区组件
  Widget _buildImagePicker() {
    return _buildInputCard(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            "上传图片 (最多9张)",
            style: TextStyle(fontWeight: FontWeight.w500),
          ),
          const SizedBox(height: 8),
          Wrap(
            spacing: 8,
            runSpacing: 8,
            children: [
              ..._images.map(
                (file) => ClipRRect(
                  borderRadius: BorderRadius.circular(8),
                  child: Image.file(
                    file,
                    width: 100,
                    height: 100,
                    fit: BoxFit.cover,
                  ),
                ),
              ),
              if (_images.length < 9)
                GestureDetector(
                  onTap: _pickImages,
                  child: Container(
                    width: 100,
                    height: 100,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(8),
                      color: Colors.grey.shade200,
                    ),
                    child: const Icon(
                      Icons.add_a_photo,
                      size: 28,
                      color: Colors.grey,
                    ),
                  ),
                ),
            ],
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xfff7f8fa),
      appBar: AppBar(title: const Text("发布租房")),
      body: Form(
        key: _formKey,
        child: ListView(
          padding: const EdgeInsets.all(12),
          children: [
            _buildInputCard(
              child: TextFormField(
                decoration: const InputDecoration(
                  hintText: '标题：如阳台房出租，近地铁',
                  border: InputBorder.none,
                ),
                style: const TextStyle(fontSize: 18),
                onSaved: (val) => _title = val ?? '',
                validator: (val) => val!.isEmpty ? '请输入标题' : null,
              ),
            ),
            _buildInputCard(
              child: TextFormField(
                decoration: const InputDecoration(
                  hintText: '租金（元/月）',
                  border: InputBorder.none,
                ),
                keyboardType: TextInputType.number,
                onSaved: (val) => _price = val ?? '',
                validator: (val) => val!.isEmpty ? '请输入租金' : null,
              ),
            ),
            _buildInputCard(
              child: TextFormField(
                decoration: const InputDecoration(
                  hintText: '位置，如朝阳望京',
                  border: InputBorder.none,
                ),
                onSaved: (val) => _location = val ?? '',
              ),
            ),
            _buildInputCard(
              child: TextFormField(
                decoration: const InputDecoration(
                  hintText: '详细描述、配套、朝向、租期等',
                  border: InputBorder.none,
                ),
                maxLines: 5,
                onSaved: (val) => _description = val ?? '',
              ),
            ),
            _buildImagePicker(),
            const SizedBox(height: 100), // 底部留白，避免被按钮遮挡
          ],
        ),
      ),
      bottomSheet: Container(
        padding: const EdgeInsets.all(16),
        width: double.infinity,
        color: Colors.white,
        child: ElevatedButton(
          onPressed: _submit,
          style: ElevatedButton.styleFrom(
            padding: const EdgeInsets.symmetric(vertical: 14),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(30),
            ),
            backgroundColor: Colors.blueAccent,
          ),
          child: const Text(
            "发布",
            style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
          ),
        ),
      ),
    );
  }
}
